package cn.likole.oj.service;

import cn.likole.oj.bean.*;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.Date;


@IocBean
public class MoneyService {

    @Inject
    private Dao dao;

    /**
     * 解决了问题后触发
     * @param solution
     */
    public void solved(Solution solution){
        if(solution.getResult()!=4) return;
        int num=dao.func(Solution.class,"count","solutionId", Cnd.where("userId","=",solution.getUserId()).and("problemId","=",solution.getProblemId()).and("result","=",4));
        if(num==0){
            User user=dao.fetch(User.class,solution.getUserId());
            int money;
            if(user.getStage()==0){//第一阶段
                money=1;
            }else{
                Problem problem=dao.fetch(Problem.class,solution.getProblemId());
                money= (int) (problem.getLevel()*10+(Math.random()*5)-(Math.random()*5));
            }
            MoneyLog moneyLog=new MoneyLog();
            moneyLog.setUserId(user.getUserId());
            moneyLog.setChangeLog(money);
            moneyLog.setTime(new Date());
            moneyLog.setReason("解决了问题"+solution.getProblemId());
            dao.insert(moneyLog);
            //更新userinfo的金币
            dao.update(UserInfo.class, Chain.makeSpecial("money","+"+money),Cnd.where("userId","=",solution.getUserId()));
        }
    }
}
